<?php

namespace App\Api\Http\Controllers\V1\In;

use App\Admin\Eloquent\Code;
use App\Api\Eloquent\User;
use App\Api\Eloquent\UserInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Ibeibeili\SinaPay\Facades\BindingBankCard;
use Ibeibeili\SinaPay\Facades\BindingBankCardAdvance;
use Ibeibeili\SinaPay\Facades\UnbindingBankCard;
use Ibeibeili\SinaPay\Facades\UnbindingBankCardAdvance;
use Ibeibeili\SinaPay\Facades\CreateHostingWithdraw;
use Ibeibeili\SinaPay\Facades\CreateHostingDeposit;
use Ibeibeili\SinaPay\Facades\SetPayPassword;
use Ibeibeili\SinaPay\Facades\ModifyPayPassword;
use Ibeibeili\SinaPay\Facades\QueryBalance;
use App\Api\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Mockery\CountValidator\Exception;
use App\Eloquent\TradeRecords;
use Illuminate\Support\Facades\Validator;


class UserMoneyController extends Controller{
    /*
     * 绑定银行卡
     */
    public function bindBankCard(Request $request){

        $r_data=$request->UserData;
        $user=User::user();
        if($user->userInfo->name_verified==0){
            return $this->my_jsonp($request->input('callback'),'',411);
        }
        if($user->phone_number_verified==0){
            return $this->my_jsonp($request->input('callback'),'',412);//请先绑定手机
        }
        if($user->userInfo->bank_card_id!=null){
            return $this->my_jsonp($request->input('callback'),'',730,'您已绑定银行卡');
        }
        $params['request_no']= microtme_format('YmdHisx');
        $params['identity_id']=$user->identity_id;
        $params['identity_type']='UID';
        $params['bank_code']=$r_data['bankcode'];//银行代码
        $params['bank_account_no']=$r_data['card'];//卡号
        $params['card_type']='DEBIT';//卡类型DEBIT or CREDIT
        $params['card_attribute']='C';//卡属性 C or B
        $params['province']=$r_data['province'];//省份
        $params['city']=$r_data['city'];//城市
        $params['verify_mode']='SIGN';//认证方式
        $params['phone_no']=$r_data['phone_number'];
        $result=BindingBankCard::send($params);
        if($result['response_code']=='APPLY_SUCCESS'){
            $data['ticket']=$result['ticket'];
            $data['bank_code']=$r_data['bankcode'];
            $data['bank_account_no']=$r_data['card'];
            Cache::put('api'.$user->identity_id.'BB',$data,10);

            return $this->my_jsonp($request->input('callback'));
        }
        if($result['response_code']=='BANK_INFO_VERIFY_FAILED'){
            return $this->my_jsonp($request->input('callback'),'',730,$result['response_message']);//银行卡号与银行不匹配
        }
        empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
        return $this->my_jsonp($request->input('callback'),'',603,$result['response_message']);//验证码发送失败
    }
    /*
     * 确认绑定银行卡
     */
    public function doBindBankCard(Request $request){
        $r_data=$request->UserData;
        $validator = Validator::make($r_data, [
            'code'=> 'min:6|max:6',
        ]);
        if($validator->fails()){
            return $this->my_jsonp($request->input('callback'),'',899);//输入信息不符合规则
        }
        if($r_data['code']==null){
            return $this->my_jsonp($request->input('callback'),'',604);//请输入验证码
        }
        $m_status=903;//绑定成功
        try{
            DB::beginTransaction();
            $user=User::user();
            $data=Cache::get('api'.$user->identity_id.'BB');
            if($data==null){
                throw new Exception('','606');//请先发送验证码
            }
            $params['ticket']=$data['ticket'];
            $params['valid_code']=$r_data['code'];
            $result=BindingBankCardAdvance::send($params);
            if($result['response_code']!='APPLY_SUCCESS'){
                empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                throw new Exception($result['response_message'],'730');//绑定失败
            }
            if($result['is_verified']!='Y'){
                empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                throw new Exception($result['response_message'],'730');//绑定失败
            }
            $userinfo=UserInfo::findOrFail($user->id);
            $userinfo->bank_code=$data['bank_code'];
            $userinfo->bank_card_number=$data['bank_account_no'];
            $userinfo->bank_card_id=$result['card_id'];
            $userinfo->save();
            $user->userInfo->bank_code=$data['bank_code'];
            $user->userInfo->bank_card_number=$data['bank_account_no'];
            $user->userInfo->bank_card_id=$result['card_id'];
            DB::commit();
        }
        catch(\Exception $e){
            DB::rollback();
            return $this->my_jsonp($request->input('callback'),'',$e->getCode(),$e->getMessage());
        }
        //绑定成功
        return $this->my_jsonp($request->input('callback'),'',$m_status);
    }
    /*
     * 解绑银行卡
     */
    public function unBindBankCard(Request $request){
        $user=User::user();
        if($user->userInfo->bank_card_id==null){
            return $this->my_jsonp($request->input('callback'),'',732,'您没有绑定银行卡');
        }
        $query_params['identity_id']=$user->identity_id;
        $query_params['identity_type']='UID';
        $query_params['account_type']='SAVING_POT';
        $query_result=QueryBalance::send($query_params);
        if($query_result['response_code']=='APPLY_SUCCESS'){
            if($query_result['balance']>0){
            return $this->my_jsonp($request->input('callback'),'',732,'请将余额提现后，再进行解绑操作');
            }
        }
        else{
            return $this->my_jsonp($request->input('callback'),'',732,$query_result['response_message']);
        }
        $params['identity_id']=$user->identity_id;
        $params['identity_type']='UID';
        $params['card_id']=$user->userInfo->bank_card_id;
        $params['advance_flag']='Y';
        $result=UnbindingBankCard::send($params);
        if($result['response_code']=='APPLY_SUCCESS'){
            $data['ticket']=$result['ticket'];
            Cache::put('api'.$user->identity_id.'UB',$data,10);
            return $this->my_jsonp($request->input('callback'));
        }
        empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
        return $this->my_jsonp($request->input('callback'),'',603,$result['response_message']);//验证码发送失败
    }
    /*
     * 确认解绑银行卡
     */
    public function doUnBindBankCard(Request $request ,$code){
        $m_status=904;//银行卡解绑成功
        try{
            DB::beginTransaction();
            $user=User::user();
            $data=Cache::pull('api'.$user->identity_id.'UB');
            if($data==null){
                throw new Exception('','606');//请先发送验证码
            }
            $params['identity_id']=$user->identity_id;
            $params['identity_type']='UID';
            $params['valid_code']=$code;
            $params['ticket']=$data['ticket'];

            $result=UnbindingBankCardAdvance::send($params);
            if($result['response_code']!='APPLY_SUCCESS'){
                empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                throw new Exception($result['response_message'],'732');//解除银行卡绑定失败
            }
            $userinfo=UserInfo::findOrFail($user->id);
            $userinfo->bank_code=null;
            $userinfo->bank_card_number=null;
            $userinfo->bank_card_id=null;
            $userinfo->save();
            $user->userInfo->bank_code=null;
            $user->userInfo->bank_card_number=null;
            $user->userInfo->bank_card_id=null;
            DB::commit();
        }
        catch(\Exception $e){
            DB::rollback();
            return $this->my_jsonp($request->input('callback'),'',$e->getCode(),$e->getMessage());
        }
        //绑定成功
        return $this->my_jsonp($request->input('callback'),'',$m_status);
    }
    /*
     * 查询银行卡
     */
    public function findBankCard(Request $request){
        $user=User::user();
        if($user->userInfo->name_verified==0){
            return $this->my_jsonp($request->input('callback'),'',411);//请先实名认证
        }
        if($user->phone_number_verified==0){
            return $this->my_jsonp($request->input('callback'),'',412);//请先绑定手机
        }
        if($user->userInfo->bank_code==null){
            return $this->my_jsonp($request->input('callback'),'',413);//请先绑定银行卡
        }
        $bank=Code::where('type_id','=','bank_code')->where('code','=',$user->userInfo->bank_code)->first();
        $data['bank']=$bank;
        $data['bank_code']=$user->userInfo->bank_code;
        $data['bank_number']=substr($user->userInfo->bank_card_number,-4);
        return $this->my_jsonp($request->input('callback'),compact('data'));
    }
    /*
     * 充值
     */
    public function payMoney(Request $request,$money){
        if($money!='0'){
            $fee=Code::where('code','=','user_pot_recharge')->first();
            $fee=explode(',',$fee->description);
            try{
                DB::beginTransaction();

                //手续费
                $user_fee=round($fee['1']*$money/100,2);

                $user=User::user();

                $params['summary']='账户充值';
                $params['out_trade_no']=createSn();//交易订单号
                $params['identity_id']=$user->identity_id;
                $params['identity_type']='UID';
                $params['amount']=$money;
                if($fee['1']!=0 ){
                    if($user_fee<0.01){
                        $user_fee=0.01;
                    }
                    $params['user_fee']=$user_fee;//用户手续费
                }
                $params['account_type']='SAVING_POT';//存钱罐账户
                $params['pay_method']='online_bank'.'^'.$money.'^SINAPAY,DEBIT,C';
                $params['extend_param']='channel_black_list^online_bank';
                $params['return_url']=$this->getNowUrl().'/bbl/html/Ucenter/Ucenter.html';

                //插入交易记录
                $trade_records = new TradeRecords;
                $trade_records->type=4;//类别
                $trade_records->sn=$params['out_trade_no'];//
                $trade_records->remarks=$params['summary'];
                $trade_records->pay_user=$user->id;
                $fee_money=round((0.2*$money/100),2);
                if($fee_money<0.01){
                    $fee_money=0.01;
                }
                $trade_records->fee_money=$fee_money-$user_fee;//平台手续费
                $trade_records->user_fee=$user_fee;//用户手续费
                $trade_records->money=$money;
                $trade_records->created_at=date('Y-m-d H:i:s');
                if(!$trade_records->save()){
                    throw new Exception('添加充值记录失败',600);
                }
                $result=CreateHostingDeposit::send($params);
                DB::commit();
            }catch(\Exception $e){
                DB::rollback();
                $code=array('600');
                if(in_array($e->getCode(),$code)){
                    $message=$e->getMessage();
                }else{
                    $message='系统错误';
                }
                return view('api.recharge',compact('message'));
            }
            return $result;
        }
        $message='充值金额不能为零';
        return view('api.recharge',compact('message'));
    }
    /*
     * 提现
     */
    public function outMoney(Request $request,$money){
        if($money!='0'){
            $fee=Code::where('code','=','user_pot_withdraw')->first();
            $fee=explode(',',$fee->description);
            try{
                DB::beginTransaction();
                //手续费
                $user_fee=round($fee['1'],2);
                $fee_money=round($fee['0'],2);
                if($fee['0']!=0 && $fee_money<0.01){
                    $fee_money=0.01;
                }
                $user=User::user();
                $params['identity_id']=$user->identity_id;
                $params['identity_type']='UID';
                $params['account_type']='SAVING_POT';
                $result=QueryBalance::send($params);
                //没有存钱罐账户
                if($result['response_code']=='NO_BASIC_ACCOUNT'){
                    throw new Exception('余额不足',414);
                }elseif($result['response_code']=='SYSTEM_ERROR'){
                    throw new Exception($result['response_message'],600);
                }elseif($result['response_code']!='APPLY_SUCCESS'){
                    empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
                    throw new Exception($result['response_message'],600);
                }
                //余额不足
                if($money>$result['available_balance']){
                    throw new Exception('余额不足',414);
                }
                $params['out_trade_no']=createSn();//交易订单号
                $params['summary']='余额提现';
                $params['identity_id']=$user->identity_id;
                $params['identity_type']='UID';
                $params['amount']=$money;
                if($fee['1']!=0){
                    if($user_fee<0.01){
                        $user_fee=0.01;
                    }
                    $params['user_fee']=$user_fee;//用户手续费
                }
                $params['account_type']='SAVING_POT';//存钱罐账户
                $params['card_id']=$user->userInfo->bank_card_id;
                $params['return_url']=$this->getNowUrl().'/bbl/html/Ucenter/Ucenter.html';


                //插入交易记录
                $trade_records = new TradeRecords;
                $trade_records->type=5;//类别
                $trade_records->sn=$params['out_trade_no'];//流水号
                $trade_records->remarks=$params['summary'];
                $trade_records->pay_user=$user->id;
                $trade_records->money=$money;
                $trade_records->fee_money=$fee_money;//平台手续费
                $trade_records->user_fee= $user_fee;//用户手续费
                $trade_records->created_at=date('Y-m-d H:i:s');
                if(!$trade_records->save()){
                    throw new Exception('添加提现记录失败',600);
                }
                $result=CreateHostingWithdraw::send($params);
                DB::commit();
            }catch(\Exception $e){
                DB::rollback();
                $code=array('414','600');
                if(in_array($e->getCode(),$code)){
                    $message=$e->getMessage();
                }else{
                    $message='系统错误';
                }
                return view('api.withdrw',compact('message'));
            }
            return $result;
        }
        $message='提现金额不能为零';
        return view('api.withdrw',compact('message'));
    }
    /*
     * 设置支付密码
     */
    public function setUserPayPassword(Request $request){
        $user=User::user();
        if($user->userInfo->name_verified==0){
            return $this->my_jsonp($request->input('callback'),'',411);//请先实名认证
        }
        if($user->phone_number_verified==0){
            return $this->my_jsonp($request->input('callback'),'',412);//请先绑定手机
        }
        if($user->userInfo->bank_code==null){
            return $this->my_jsonp($request->input('callback'),'',413);//请先绑定银行卡
        }
        //修改支付密码
        if($user->userInfo->is_set_pay_password==1){
            $r_result=ModifyPayPassword::send(['identity_id' => $user->identity_id,'identity_type'=>'UID','return_url'=>$this->getNowUrl().'/bbl/html/Ucenter/Ucenter.html']);
            if($r_result['response_code'] != 'APPLY_SUCCESS'){
                return $this->my_jsonp($request->input('callback'),'',600,$r_result['response_message']);
            }
            $r_url=$r_result['redirect_url'];
            return $this->my_jsonp($request->input('callback'),compact('r_url'));
        }
        //设置支付密码
        $result = setPayPassword::send(['identity_id' => $user->identity_id,'identity_type'=>'UID','return_url'=>$this->getNowUrl().'/bbl/html/Ucenter/Ucenter.html']);
        if($result['response_code'] != 'APPLY_SUCCESS'){
            return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
        }
        $r_url=$result['redirect_url'];
        return $this->my_jsonp($request->input('callback'),compact('r_url'));
    }
}